package com.example.exception.exception;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class GlobalException3 implements HandlerExceptionResolver {
    /**
     * 也需要是配置类
     * 优点：可以拦截所有Controller中的异常
     *      可以传递异常对象
     * @param request
     * @param response
     * @param handler 此次产生异常对象的handler
     * @param e
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if(e instanceof NullPointerException){
            modelAndView.setViewName("/exceptionPage");
        }else if( e instanceof RuntimeException){
            modelAndView.setViewName("");
        }
        modelAndView.addObject("exception", e.toString());
        modelAndView.addObject("stackTrace", e.getStackTrace());
        modelAndView.addObject("errorInfo", "空指针异常");
        modelAndView.addObject("errorMessage", e.getMessage());
        modelAndView.addObject("cause", e.getCause());

        return modelAndView;
    }
}
